<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button.backtop{
      position: fixed;
      right: 50px;
      bottom: 50px;
    }
    button.btn{
      position: fixed;
      left: 50px;
      top: 50px;
    }
  </style>
</head>
<body style="height: 3000px">
  <div id="app">
    <button class="btn" @click="isShow=!isShow">{{isShow? '隐藏': '显示'}}</button>
    <button class="backtop" v-if="isShow" v-backtop="200">回到顶部</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    // 定义指令回到顶部
    Vue.directive('backtop', {
      inserted(el, binding){
        el.style.display = 'none';
        // 添加滚动事件 判断滚动距离决定 按钮显示和隐藏
        window.onscroll = () => {
          const sTop = document.documentElement.scrollTop|| document.body.scrollTop;
          console.log(sTop);
          if(sTop>binding.value){
            el.style.display = 'block';
          }else{
            el.style.display = 'none';
          }
        }

        el.onclick = () => {
          // 点击按钮回到顶部
          window.scrollTo(0, 0);
        }
      },
      unbind(){
        console.log('指令解绑');
        window.onscroll = null;
      }
    })
    const vm = new Vue({
      el: '#app',
      data: {
        isShow: true
      }
    })
  </script>
</body>
</html>